package com.bg.rpc.server;

import com.bg.rpc.code.RPCDecoder;
import com.bg.rpc.code.RPCEncoder;
import com.bg.rpc.constant.Constant;
import com.bg.rpc.protocol.RPCRequest;
import com.bg.rpc.protocol.RPCResponse;
import com.bg.rpc.service.IDiff;
import com.bg.rpc.service.impl.IDiffImpl;
import com.bg.rpc.utils.IpUtils;
import com.bg.rpc.utils.XmlUtil;
import com.bg.rpc.zk.ServiceRegistry;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: zhengshunzhi
 * @Date: 2018/8/24 22:11
 * @Description: nioServer的半包处理，还有服务注册，以及相应服务的确定。
 */
public class RPCServer {

    private Map<String, String> getServices() {
        Map<String, String> handleMap = new ConcurrentHashMap<>();
        // 先将服务确定好，才能调用，不允许客户端自动添加服务
        XmlUtil.readXml(Constant.SERVER_INTERFACE_PATH).forEach(m -> {
            handleMap.put(m.get(Constant.SERVER_INTERFACE_KEY), m.get(Constant.SERVER_INTERFACE_VALUE));
        });
        return handleMap;
    }

    private void bind(int port) {
        // 连接处理group
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //EventLoopGroup默认的线程数是CPU核数的二倍
        // 事件处理group
        EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);
        Map<String, String> handlerMap = getServices();
        try {
            ServerBootstrap b = new ServerBootstrap();
            // 绑定处理group
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
                    // 保持连接数
                    .option(ChannelOption.SO_BACKLOG, 1024 * 1024)
                    // 有数据立即发送
                    .option(ChannelOption.TCP_NODELAY, true)
                    // 保持连接
                    .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_RCVBUF, 10 * 1024).option(ChannelOption.SO_SNDBUF, 10 * 1024)
                    //Boss线程池内存池配置
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    //work内存池配置
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childOption(ChannelOption.SO_KEEPALIVE, true)
                    // 处理新连接
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS)).addLast(new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2)).addLast(new RPCDecoder(RPCRequest.class)).addLast(new LengthFieldPrepender(2)).addLast(new RPCEncoder(RPCResponse.class)).addLast(new RPCServerHandler(handlerMap));
                        }
                    });
            //绑定端口等待数据同步
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


    public static String getAddress() {
        InetAddress host = null;
        try {
            // 获取本机ip
            host = IpUtils.getCurrentIp();
            //此方法不安全
            //host = InetAddress.getLocalHost();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String address = host.getHostAddress();
        return address;
    }

    public void initService(int port) {
        //创建服务端实例
        ServiceRegistry serviceRegistry = new ServiceRegistry();
        //获取当前ip
        String ip = getAddress();
        //向zookeeper注册服务地址
        serviceRegistry.register(ip + Constant.ZK_IP_SPLIT + port);
        //启动服务
        bind(port);
    }
}

